import 'package:animation_effect_demo/src/effects/effect_template.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_colorpicker/flutter_colorpicker.dart';

import '../bean/text_data_dto.dart';
import '../effects/text_operation.dart';
import '../widget/text_animation_container.dart';

class EditTextTemplatePage extends StatefulWidget{
  final EffectOperation operation;
  const EditTextTemplatePage({super.key,required this.operation});

  @override
  State<StatefulWidget> createState() => _EditTextTemplatePageState();

}

class _EditTextTemplatePageState extends State<EditTextTemplatePage>{

  @override
  void initState() {
    operation = widget.operation;
    TextOperation textOperation = operation.textOperation!;
    textContent = textOperation.textStyleData.content;
    selectedFont = textOperation.textStyleData.fontStyle;
    selectedFontSize = textOperation.textStyleData.fontSize;
    selectedColor = textOperation.textAttrData.fontColors.first;
    // backgroundColor = textOperation.textAttrData.backgroundStyle!.backgroundColor!;
    dynamicType = textOperation.textEffectData.animationType;
    super.initState();
  }

  final TextEditingController _controller = TextEditingController(text: '你好,Hello!');
  List<String> fontList = [
    'SongTi',
    'HeiWei',
    'Poppins',
    'Typeface',
    'Emoji',
    'font01',
    'font02',
    'font03',
    'font04',
    'font05',
    'font06',
    'font07',
    'font08',
    'font09',
    'font10',
    'font11',
    'font12',
    'font13',
    'font14',
    'font15',
    'font16',
    'font17',
    'font18',
    'font19',
    'font20',
    'font21'
  ];
  late String textContent;
  String selectedFont = 'SongTi';
  int selectedFontSize = 10;
  Color selectedColor = Colors.red;
  Color backgroundColor = Colors.blue;
  bool enableBackground = false;
  AnimationType dynamicType = AnimationType.fixed;
  late EffectOperation operation;
  TextDataDTO? textData;


  Future<void> updateTextOperation() async {
    final styleData = TextStyleData(content: textContent, fontStyle: selectedFont, fontSize: selectedFontSize, fontName: selectedFont);
    final attrData = TextAttrData(fontColors: [selectedColor],backgroundStyle: BackgroundStyle(type: StyleType.color,backgroundColor: enableBackground?backgroundColor:Colors.transparent));
    final effectData = TextEffectData(animationType: dynamicType,speed: 90,brightness: 100);
    final textOperation = TextOperation(textStyleData: styleData,textAttrData: attrData,textEffectData: effectData);
    operation = operation.copyWith(textOperation: textOperation);
  }

  _showFontColorDialog() {
    FocusScope.of(context).requestFocus(FocusNode());
    showDialog(
        context: context,
        builder: (_) {
          var color = selectedColor;
          return AlertDialog(
            title: const Text('Pick a color!'),
            content: SingleChildScrollView(
              child: ColorPicker(
                pickerColor: selectedColor,
                onColorChanged: (value) {
                  color = value;
                },
              ),
            ),
            actions: <Widget>[
              ElevatedButton(
                child: const Text('Got it'),
                onPressed: () {
                  selectedColor = color;
                  updateTextOperation();
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        });
  }

  _showBackgroundColorDialog() {
    FocusScope.of(context).requestFocus(FocusNode());
    showDialog(
        context: context,
        builder: (_) {
          var color = backgroundColor;
          return AlertDialog(
            title: const Text('Pick a color!'),
            content: SingleChildScrollView(
              child: ColorPicker(
                pickerColor: backgroundColor,
                onColorChanged: (value) {
                  color = value;
                },
              ),
            ),
            actions: <Widget>[
              ElevatedButton(
                child: const Text('Got it'),
                onPressed: () {
                  backgroundColor = color;
                  updateTextOperation();
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(
              height: 160,
              child: GalleryAnimationContainer(
                displayWidth: 64,
                displayHeight: 16,
                operation: operation,
              ),
            ),
            Expanded(
                flex: 4,
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      Container(
                        margin: const EdgeInsets.all(10.0),
                        padding: const EdgeInsets.all(5.0),
                        decoration: BoxDecoration(
                            color: Colors.grey.shade200,
                            borderRadius:
                            BorderRadius.all(Radius.circular(6.0))),
                        child: TextField(
                          controller: _controller,
                          style: TextStyle(
                              fontSize: selectedFontSize.toDouble(),
                              fontFamily: operation.textOperation!.textStyleData.fontStyle,
                              color: selectedColor),
                          decoration: InputDecoration(border: InputBorder.none),
                          maxLines: 1,
                          onChanged: (value) {
                            setState(() {
                              textContent = value;
                              updateTextOperation();
                            });
                          },
                        ),
                      ),
                      ListTile(
                        leading: Text(
                          '字体:',
                          style: TextStyle(fontSize: 18.0),
                        ),
                        title: Text(
                          selectedFont,
                          textAlign: TextAlign.end,
                        ),
                        onTap: () {
                          FocusScope.of(context).requestFocus(FocusNode());
                          showModalBottomSheet(
                              context: context,
                              barrierColor: Colors.black.withAlpha(100),
                              builder: (_) {
                                return ListView(
                                  padding: EdgeInsets.symmetric(vertical: 10.0),
                                  children: fontList
                                      .map((e) => GestureDetector(
                                    onTap: () {
                                      Navigator.of(context).pop(e);
                                    },
                                    behavior: HitTestBehavior.opaque,
                                    child: Column(
                                      children: [
                                        Padding(
                                          padding:
                                          const EdgeInsets.all(8.0),
                                          child: Center(
                                              child: Text(
                                                e,
                                                style:
                                                TextStyle(fontSize: 18),
                                              )),
                                        ),
                                        Divider()
                                      ],
                                    ),
                                  ))
                                      .toList(),
                                );
                              }).then((value) {
                            if (value != null) {
                              selectedFont = value;
                              setState(() {
                                updateTextOperation();
                              });
                            }
                          });
                        },
                        trailing: Icon(Icons.keyboard_arrow_right),
                      ),
                      ListTile(
                        leading: Text(
                          '字号:',
                          style: TextStyle(fontSize: 18.0),
                        ),
                        title: Row(
                          children: [
                            Expanded(
                              child: Slider(
                                  min: 4.0,
                                  max: 80.0,
                                  value: selectedFontSize.toDouble(),
                                  onChanged: (value) {
                                    selectedFontSize = value.toInt();
                                    setState(() {
                                      updateTextOperation();
                                    });
                                  }),
                            ),
                            Text(selectedFontSize.toString())
                          ],
                        ),
                      ),
                      ListTile(
                        leading: Text(
                          '字体颜色:',
                          style: TextStyle(fontSize: 18.0),
                        ),
                        title: Align(
                          alignment: Alignment.centerRight,
                          child: Container(
                            width: 30.0,
                            height: 30.0,
                            decoration: BoxDecoration(
                                color: selectedColor,
                                borderRadius: BorderRadius.circular(4)),
                          ),
                        ),
                        onTap: _showFontColorDialog,
                        trailing: Icon(Icons.keyboard_arrow_right),
                      ),
                      ListTile(
                        leading: Text(
                          '背景颜色:',
                          style: TextStyle(fontSize: 18.0),
                        ),
                        title: Align(
                          alignment: Alignment.centerRight,
                          child: Container(
                            width: 30.0,
                            height: 30.0,
                            decoration: BoxDecoration(
                                color: backgroundColor,
                                borderRadius: BorderRadius.circular(4)),
                          ),
                        ),
                        onTap: _showBackgroundColorDialog,
                        trailing: Switch(
                            value: enableBackground,
                            onChanged: (value) {
                              enableBackground = !enableBackground;
                              setState(() {
                                updateTextOperation();
                              });
                            }),
                      ),
                      ListTile(
                        leading: Text(
                          '动态效果:',
                          style: TextStyle(fontSize: 18.0),
                        ),
                        subtitle: Wrap(
                          children: AnimationType.values
                              .map((e) => Padding(
                            padding: const EdgeInsets.symmetric(
                                horizontal: 4.0),
                            child: TextButton(
                              style: TextButton.styleFrom(
                                  foregroundColor: e == dynamicType
                                      ? Colors.blue
                                      : Colors.grey,
                                  shape: RoundedRectangleBorder(
                                      borderRadius:
                                      BorderRadius.circular(6),
                                      side: BorderSide(
                                          color: e == dynamicType
                                              ? Colors.blue
                                              : Colors.grey))),
                              onPressed: () {
                                setState(() {
                                  dynamicType = e;
                                  updateTextOperation();
                                });
                              },
                              child: Text(e.name),
                            ),
                          ))
                              .toList(),
                        ),
                      ),
                      SizedBox(
                        height: 20.0,
                      ),
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 20.0),
                        child: ElevatedButton(
                            onPressed: () {
                            },
                            child: Center(child: Text('预览'))),
                      )
                    ],
                  ),
                ))
          ],
        ),
      ),
    );;
  }

}